package com.yueya.api.news;

import net.sf.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yueya.basic.dict.model.Dict;
import com.yueya.basic.news.content.model.Content;
import com.yueya.basic.news.content.model.ContentZan;
import com.yueya.common.service.BaseService;
import com.yueya.common.util.DateUtil;
import com.yueya.common.util.UUIDGenerator;
import com.yueya.config.GlobalParam;

public class INewsService extends BaseService {

	/**
	 * 获取列表
	 * 
	 * @param jo
	 * @return
	 */
	public Map<String, Object> getPageList(JSONObject jo) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> error = new HashMap<String, Object>();

		if (containsKey(jo, "pgn", "pgs")) {

			if (jo.containsKey("pgn")) {
				pageNumber = jo.getInt("pgn");
			}
			if (jo.containsKey("pgs")) {
				pageSize = jo.getInt("pgs");
			}

			String select = "select c.content_id contentid,c.content_type contenttype,c.title,c.create_time createtime,c.view_num viewnum,( CASE  c.content_img_path WHEN null THEN  c.content_img_path ELSE CONCAT('"
					+ GlobalParam.getAttUrl() + "' ,c.content_img_path )  END  ) contentimgpath,"
					+ "(select count(cz.content_zan_id) from t_content_zan cz where cz.content_id = c.content_id and cz.del_flag='0') zannum ";
			StringBuffer sql = new StringBuffer(
					" from t_content c left join t_content_text ct on ct.content_id = c.content_id where c.del_flag = '0' ");

			// 栏目ID
			if (jo.containsKey("subject")) {
				String subject = jo.getString("subject");
				if (StrKit.notBlank(subject)) {
					sql.append(" and c.subject_id = '" + subject + "'");
				}
			}
			// 新闻标题
			if (jo.containsKey("title")) {
				String title = jo.getString("title");
				if (StrKit.notBlank(title)) {
					sql.append(" and c.title like '%" + title + "%'");
				}
			}

			// 新闻类型
			if (jo.containsKey("contenttype")) {
				String contenttype = jo.getString("contenttype");
				if (StrKit.notBlank(contenttype)) {
					sql.append(" and c.content_type = '" + contenttype + "'");
				}
			}
			sql.append(" order by c.is_top desc,c.is_essence desc,c.order_num,c.create_time desc");

			Page<Record> page = Db.paginate(pageNumber, pageSize, select.toString(), sql.toString());

			if (page != null) {
				map.put("result", true);
				List<Record> list = page.getList();
				Record r = null;
				for (int i = 0; i < list.size(); i++) {
					r = list.get(i);
					// 发布时间格式化
					String createTime = r.getStr("createtime");
					if (StrKit.notBlank(createTime)) {
						r.set("createtime", DateUtil.betweenBeforeTime(createTime));
					}

				}
				map.put("data", list);
				map.put("size", page.getTotalRow());
				map.put("pgn", page.getPageNumber());
				map.put("pgs", page.getPageSize());
				map.put("totalPage", page.getTotalPage());
			} else {
				map.put("result", true);
				map.put("size", 0);
			}
		} else {
			map.put("result", false);
			error.put("errcode", "YY.INVALID_JSON_PARAM");
			error.put("errmsg", "JSON参数不合法");
			map.put("error", error);
		}
		return map;
	}

	// 获取明细
	public Map<String, Object> getDetail(JSONObject jo) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> error = new HashMap<String, Object>();

		if (containsKey(jo, "contentid")) {
			String contentId = jo.getString("contentid");
			String sql = "select b.content_id id,b.title title,b.create_time createtime,ct.content_text contenttext,ct.content_html contenthtml,b.content_img_path contentimgpath,b.audio_path audiopath,b.video_path videopath "
					+ " ,(select count(cz.content_zan_id) from t_content_zan cz where cz.content_id = b.content_id and cz.del_flag='0') zannum "
					+ " from t_content b " + " left join t_content_text ct on ct.content_id = b.content_id "
					+ " where b.content_id = ?";
			Record content = Db.findFirst(sql, contentId);
			if (content != null) {
				// 富文本内容
				content.set("contenttext",
						content.getStr("contenttext") == null || "null".equals(content.getStr("contenttext")) ? ""
								: content.getStr("contenttext"));
				content.set("contenthtml",
						content.getStr("contenthtml") == null || "null".equals(content.getStr("contenthtml")) ? ""
								: content.getStr("contenthtml"));

				// 图片路径
				if (StrKit.notBlank(content.getStr("contentimgpath"))) {
					System.out.println(Dict.dao.getValue("attachment_url"));
					content.set("contentimgpath", GlobalParam.getAttUrl() + content.getStr("contentimgpath"));
				}

				// 音频路径
				if (StrKit.notBlank(content.getStr("audiopath"))) {
					if (!content.getStr("audiopath").startsWith("http:/")) {
						content.set("audiopath", GlobalParam.getAttUrl() + content.getStr("audiopath"));
					}
				}

				// 视频路径
				if (StrKit.notBlank(content.getStr("videopath"))) {
					if (!content.getStr("videopath").startsWith("http:/")) {
						content.set("videopath", GlobalParam.getAttUrl() + content.getStr("videopath"));
					}
				}

				Content c = Content.dao.findById(contentId);
				c.set("view_num", c.getInt("view_num") + 1);
				c.update();
				map.put("result", true);
				map.put("data", content);
			} else {
				map.put("result", false);
				error.put("errcode", "NO_RECORD");
				error.put("errmsg", "操作失败");
				map.put("error", error);
			}

		} else {
			map.put("result", false);
			error.put("errcode", "INVALID_JSON_PARAM");
			error.put("errmsg", "JSON参数不合法");
			map.put("error", error);
		}

		return map;
	}

	// 点赞
	public Map<String, Object> setZan(JSONObject jo) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> error = new HashMap<String, Object>();

		if (containsKey(jo, "contentid", "userid")) {
			String contentId = jo.getString("contentid");
			String userId = jo.getString("userid");

			String sql = "select content_zan_id from t_content_zan where content_id = ? and user_id = ? ";
			ContentZan contentZan = ContentZan.dao.findFirst(sql, contentId, userId);
			boolean bl = false;
			if (contentZan == null) {
				ContentZan cz = new ContentZan();
				cz.set("content_zan_id", UUIDGenerator.getUUID());
				cz.set("user_id", userId);
				cz.set("content_id", contentId);
				cz.set("create_time", DateUtil.getDate(DateUtil.timeFormat));
				bl = cz.save();
			} else {

				bl = contentZan.update();
			}

			if (bl) {
				map.put("result", true);
			} else {
				map.put("result", false);
				error.put("errcode", "NO_RECORD");
				error.put("errmsg", "操作失败");
				map.put("error", error);
			}

		} else {
			map.put("result", false);
			error.put("errcode", "INVALID_JSON_PARAM");
			error.put("errmsg", "JSON参数不合法");
			map.put("error", error);
		}

		return map;
	}

	// 点赞 取消
	public Map<String, Object> zan(JSONObject jo) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> error = new HashMap<String, Object>();

		if (containsKey(jo, "contentid", "userid")) {
			String contentId = jo.getString("contentid");
			String userId = jo.getString("userid");

			String sql = "select content_zan_id from t_content_zan where  content_id = ?  and user_id = ? ";
			ContentZan contentZan = ContentZan.dao.findFirst(sql, contentId, userId);
			boolean bl = false;
			int flag = 1;
			if (contentZan == null) {
				ContentZan cz = new ContentZan();
				cz.set("content_zan_id", UUIDGenerator.getUUID());
				cz.set("user_id", userId);
				cz.set("content_id", contentId);
				cz.set("create_time", DateUtil.getDate(DateUtil.timeFormat));
				bl = cz.save();
				flag = 1;
			} else {

				bl = contentZan.delete();
				flag = 0;
			}

			if (bl) {
				map.put("result", true);
				map.put("flag", flag);
			} else {
				map.put("result", false);
				error.put("errcode", "NO_RECORD");
				error.put("errmsg", "操作失败");
				map.put("error", error);
			}

		} else {
			map.put("result", false);
			error.put("errcode", "INVALID_JSON_PARAM");
			error.put("errmsg", "JSON参数不合法");
			map.put("error", error);
		}

		return map;
	}

	// 取消点赞
	public Map<String, Object> cancelZan(JSONObject jo) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> error = new HashMap<String, Object>();

		if (containsKey(jo, "contentid", "userid")) {
			String contentId = jo.getString("contentid");
			String userId = jo.getString("userid");

			String sql = "select content_zan_id from t_content_zan where content_id = ? and user_id = ? ";
			ContentZan contentZan = ContentZan.dao.findFirst(sql, contentId, userId);
			boolean bl = false;
			if (contentZan != null) {
				contentZan.set("del_flag", "1");
				bl = contentZan.update();
			}

			if (bl) {
				map.put("result", true);
			} else {
				map.put("result", false);
				error.put("errcode", "NO_RECORD");
				error.put("errmsg", "操作失败");
				map.put("error", error);
			}

		} else {
			map.put("result", false);
			error.put("errcode", "INVALID_JSON_PARAM");
			error.put("errmsg", "JSON参数不合法");
			map.put("error", error);
		}

		return map;
	}

	public Map<String, Object> getZanList(JSONObject jo) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> error = new HashMap<String, Object>();

		if (containsKey(jo, "contentid")) {
			String contentId = jo.getString("contentid");
			String sql = "select  z.content_zan_id,u.user_name as  username from t_content_zan z ,t_user u  where  z.user_id = u.user_id and z.content_id = ? ";
			List<ContentZan> list = ContentZan.dao.find(sql, contentId);
			map.put("result", true);
			map.put("data", list);
			map.put("size", list.size());
		} else {
			map.put("result", false);
			error.put("errcode", "INVALID_JSON_PARAM");
			error.put("errmsg", "JSON参数不合法");
			map.put("error", error);
		}

		return map;
	}

	public Map<String, Object> getSubjectList(JSONObject jo) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> error = new HashMap<String, Object>();

		if (containsKey(jo)) {

			StringBuffer sql = new StringBuffer(
					" select s.subject_id subjectid,s.subject_name subjectname,s.parent_id parentid,s.order_id orderid,s.level,s.create_time createtime ");
			sql.append(" from t_subject s  where s.del_flag = '0' ");

			// 栏目ID
			if (jo.containsKey("parentid")) {
				String parentId = jo.getString("parentid");
				if (StrKit.notBlank(parentId)) {
					sql.append(" and s.parent_id = '" + parentId + "'");
				}
			}

			// 栏目层级
			if (jo.containsKey("level")) {
				String level = jo.getString("level");
				if (StrKit.notBlank(level)) {
					sql.append(" and s.level = '" + level + "'");
				}
			}

			sql.append(" order by s.order_id asc,s.create_time desc");

			List<Record> subjectList = Db.find(sql.toString());

			if (subjectList != null) {

				map.put("result", true);
				map.put("data", subjectList);
				map.put("size", subjectList.size());
			} else {
				map.put("result", true);
				map.put("size", 0);
			}
		} else {
			map.put("result", false);
			error.put("errcode", "YY.INVALID_JSON_PARAM");
			error.put("errmsg", "JSON参数不合法");
			map.put("error", error);
		}
		return map;
	}

}
